﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries the Hotlap chart on LfsWorld.
	/// </summary>
	public class HotlapChartQuery : LfsWorldQuery<HotlapChartEntry>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="HotlapChartQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public HotlapChartQuery(LfsWorldContext context)
			:base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		/// <returns></returns>
		protected override string GetUrl()
		{

			string url = LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "ch");

			url += string.Format("&track={0}&car={1}", ExpressionValues["TrackIdent"].Value, ExpressionValues["Car"].Value);

			if (ExpressionValues.ContainsKey("SteeringMethod"))
			{
				url += "&control=" + ExpressionValues["SteeringMethod"].Value;
			}

			return url;
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<HotlapChartEntry> ProcessResponse(string responseData)
		{
			XDocument doc = XDocument.Parse(responseData);

			if (doc.Root.Name == "ch_data")
			{

				foreach (var node in doc.Descendants("entry"))
				{
					HotlapChartEntry entry = new HotlapChartEntry();

					entry.RacerName = node.Element("racername").Value.StripLfsColours();
					entry.Id = Convert.ToInt32(node.Element("id_hl").Value);
					entry.TrackIdent = (string)ExpressionValues["TrackIdent"].Value;
					entry.TrackName = Utility.CircuitNameFactory.GetNameFromIdent(entry.TrackIdent);
					entry.Car = (string)ExpressionValues["Car"].Value;
					entry.Split1 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split1").Value));
					entry.Split2 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split2").Value));
					entry.Split3 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split3").Value));
					entry.LapTime = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("laptime").Value));
					entry.Flags = (HotlapFlags)Convert.ToInt32(node.Element("flags_hlaps").Value);

					yield return entry;
				}

			}
		}
	}
}
